package com.market2.session;

import java.util.List;

import javax.annotation.PostConstruct;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.jboss.ejb3.annotation.RemoteBinding;

import com.market2.dto.ContratDto;
import com.market2.model.Contrat;
import com.market2.utils.EntityManagerThreadLocal;
import com.market2.utils.Globals;
import com.market2.utils.converter.ConverterUtil;

/**
 * Session Bean implementation class Contrat
 */

@Stateless @RemoteBinding(jndiBinding="Market2EAR/ContratManager/remote")
public class ContratManager implements ContratManagerRemote
{
	@PersistenceContext(unitName=Globals.PERSISTENCE_UNIT_NAME)
	private EntityManager entityManager;
	
	@PostConstruct
	void init() {
		EntityManagerThreadLocal.set(entityManager);
	}

	@Override
	public void enregistrerContrat(ContratDto contrat)
	{
		Contrat c = ConverterUtil.convertFrom(contrat, Contrat.class);
		entityManager.persist(c);
		entityManager.flush();
	}

	@Override
	public ContratDto getContratByNumero(Integer numero)
	{
		Contrat c = entityManager.find(Contrat.class, numero);
		return ConverterUtil.convertTo(c, ContratDto.class);
	}

	@Override
	public List<ContratDto> getContratByInvestisseur(String investisseur)
	{
		Query query = entityManager.createQuery("from Contrat c where c.titulaire.login = :investisseur").
			setParameter("investisseur", investisseur);
		
		@SuppressWarnings("unchecked")
		List<Contrat> queryResult = query.getResultList();
		
		return ConverterUtil.convertTo(queryResult, ContratDto.class);
	}

	@Override
	public List<ContratDto> getAllContrats()
	{
		Query query = entityManager.createQuery("from Contrat");
	
		@SuppressWarnings("unchecked")
		List<Contrat> queryResult = query.getResultList();
	
		return ConverterUtil.convertTo(queryResult, ContratDto.class);
	}
}
